package middleware

import (
	"awesomeProject/app/service"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"

	"awesomeProject/app/model"
	"awesomeProject/app/response"
	"awesomeProject/util"
)

var (
	shopSrv   service.ShopSrv
	casBinSrv service.CasbinSrv
)

func RBACHandler() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		user, _ := ctx.Get("user")
		userObj := user.(model.User)

		roleIdStrList := casBinSrv.QueryUserRoleIds(userObj.UUID)
		for _, role := range roleIdStrList {
			if role.V1 == "1" {
				userObj.SuperAdmin = true
				break
			}
		}
		if userObj.SuperAdmin {
			_, companyShops := shopSrv.QueryShopIdsByUser(userObj)
			userObj.ShopIds = companyShops
			ctx.Set("user", userObj)
			ctx.Next()
			return
		}

		// 获取请求的URI
		obj := ctx.FullPath()
		// 获取请求方法
		act := ctx.Request.Method
		sub := userObj.UUID.String()
		var sEnforcer util.SEnforcer
		ok, err := sEnforcer.Enforce(sub, obj, act)
		if err != nil {
			log.Fatalf("err: enforce %s", err)
		}
		if !ok {
			ctx.AbortWithStatusJSON(http.StatusForbidden, response.ErrForbidden)
			return
		}
		ctx.Set("user", userObj)
		ctx.Next()
	}
}
